<?php
// +----------------------------------------------------------------------
// | likeshop开源商城系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | gitee下载：https://gitee.com/likeshop_gitee
// | github下载：https://github.com/likeshop-github
// | 访问官网：https://www.likeshop.cn
// | 访问社区：https://home.likeshop.cn
// | 访问手册：http://doc.likeshop.cn
// | 微信公众号：likeshop技术社区
// | likeshop系列产品在gitee、github等公开渠道开源版本可免费商用，未经许可不能去除前后端官方版权标识
// |  likeshop系列产品收费版本务必购买商业授权，购买去版权授权后，方可去除前后端官方版权标识
// | 禁止对系统程序代码以任何目的，任何形式的再发布
// | likeshop团队版权所有并拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeshop.cn.team
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\logic\GoodsLogic;
use app\common\model\OrderLog;
use app\admin\logic\OrderLogic;
use app\admin\logic\UserLogic;
use app\common\model\Client_;
use app\common\model\Order as CommonOrder;
use app\common\model\Pay;
use think\Db;

class Order extends AdminBase
{
    /**
     * User: 意象信息科技 mjf
     * Desc: 订单列表
     */
    public function lists()
    {
        $get = $this->request->get();
        if(empty($get['start_time']) || empty($get['end_time'])){
            // 默认今天
            $start_time = date('Y-m-d H:i:s', strtotime(date('Y-m-d'),time()));
            $end_time = date('Y-m-d H:i:s',strtotime($start_time)+86400);

        }
        if ($this->request->isAjax()) {
            $get = $this->request->get();
//            if($start_time && $end_time){
//                $get['start_time']=$start_time;
//                $get['end_time']=$end_time;
//            }
//            var_dump($get);
            $this->_success('', OrderLogic::lists($get));
        }


        $tableCount = OrderLogic::tableCount($get);
//        var_dump($tableCount);
        $this->assign('tableCount', $tableCount);
        $this->assign('start_time', $start_time);
        $this->assign('end_time', $end_time);
        $this->assign('order_status', CommonOrder::getOrderStatus(true));
        $this->assign('order_type', CommonOrder::getOrderType(true));
        $this->assign('pay_way', Pay::getPayWay(true));
        $this->assign('delivery_type', CommonOrder::getDeliveryType(true));
        $this->assign('order_source', Client_::getClient(true));
        return $this->fetch();
    }

    public function exportFile()
    {
        $get = $this->request->get();
        $this->_success('', OrderLogic::exportFile($get));
    }

    /**
     * User: 意象信息科技 mjf
     * Desc: 订单详情
     */
    public function detail()
    {
        $id = $this->request->get('id');

        $detail = OrderLogic::getDetail($id);
        $this->assign('detail', $detail);
        $this->assign('logs', OrderLog::getOrderLog($id));
        return $this->fetch();
    }

    /**
     * User: 意象信息科技 mjf
     * Desc: 取消订单
     */
    public function cancel()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post('');
            $check = $this->validate($post, 'app\admin\validate\Order.cancel');
            if (true !== $check) {
                $this->_error($check);
            }
            $res = OrderLogic::cancel($post['order_id'], $this->admin_id);
            if ($res === true) {
                $this->_success('取消成功');
            }
            $this->_error($res);
        }
    }

    /**
     * User: 意象信息科技 mjf
     * Desc: 删除订单
     */
    public function del()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post('');
            $check = $this->validate($post, 'app\admin\validate\Order.del');
            if (true !== $check) {
                $this->_error($check);
            }
            OrderLogic::del($post['order_id'], $this->admin_id);
            $this->_success('删除成功');
        }
    }

    /**
     * User:
     * Desc: 用户下单
     */
    public function delivery()
    {
        $id = $this->request->get('id');
        $goods_list = Db::name('goods')
            ->where(['del'=>0,'status'=>1])
            ->order('id desc')
            ->select();
        $user_list = Db::name('user')
            ->where(['del'=>0])
            ->order('id desc')
            ->select();
        $this->assign('name', json_encode([['id'=>1,'name'=>'zhangsan'],['id'=>2,'name'=>'zhangsan2']]));
        $this->assign('goods_list', $goods_list);
        $this->assign('user_list', $user_list);
        $Common = new Common();
        $bottle_site_list = $Common->selectBottleSite();
//        $detail = OrderLogic::getDetail($id);
//        $this->assign('detail', $detail);
//        $this->assign('express', OrderLogic::express());
        return $this->fetch();
    }
    public function firstUser()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post('id');
            if ( $id <= 0) {
                $this->_error("id非法");
            }
            $data = UserLogic::getUser($id);
            $this->_success('查询成功',$data);
        }
    }
    public function countPrice(){
        if ($this->request->isAjax()) {
            $data = $this->request->post('data');
            $user_id = $this->request->post('user_id');
            if ( empty($data) ) {
                $this->_error("参数非法");
            }
            // 钢瓶押金
             $bottle_deposit = 0;
            // 钢瓶租金
            $settle_bottle_rent=0;
            // 楼层费
            $floor_amount=0;
            // 气价
            $bottle_amount=0;
            // 商品增购
            $good_price = 0;
            // 总价格
            $order_amount=0;
            // 查询商品价格
            foreach($data as $k=>$v){
                $goodsData = Db::name('goods')->where('id',$v['good_id'])->field('id,name,type,price')->find();
                if($goodsData){
                    if( $goodsData['type'] == 1){
                        //主产品
                        $bottle_amount += $goodsData['price']*$v['number'];
                        $bottle_deposit += 150*$v['number'];
                    }
                    if( $goodsData['type'] == 2){
                        //增购产品
                        $good_price += $goodsData['price']*$v['number'];
                    }
                }
            }
            //钢瓶租金
            $settle_bottle_rent = Db::name('bottle_rent_log')->where([
                'user_id'=>$user_id,
                'if_pay'=>0
            ])->sum('pay_amount');
            //楼层费
            $user = Db::name('user')->where([
                'id'=>$user_id,
                'if_elevator'=>0
            ])->value('floor');
            if($user!=false){
                //查看配置表
                $config = Db::name('config')->where([
                    'type'=>'pay',
                    'name'=>'floor'
                ])->value('value')??3;
                $floor_amount = $config*$user;
            }
            $responseData = [
                'bottle_deposit'=>$bottle_deposit,
                'settle_bottle_rent'=>$settle_bottle_rent,
                'floor_amount'=>$floor_amount,
                'bottle_amount'=>$bottle_amount,
                'good_price'=>$good_price,
                'order_amount'=>$bottle_deposit+$settle_bottle_rent+$floor_amount+$bottle_amount+$good_price
            ];
            $this->_success('查询成功',$responseData);
        }
    }
    /**
     * User: 意象信息科技 mjf
     * Desc: 下单操作
     */
    public function deliveryHandle()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post('');
//            $check = $this->validate($post, 'app\admin\validate\Order.delivery');
//            if (true !== $check) {
//                $this->_error($check);
//            }
//            OrderLogic::deliveryHandle($post, $this->admin_id);
            // 查询商品信息
            $goods_id = [];
            $bottle_num=0;
            $new_bottle_num=0;
            foreach($post['goods_id'] as $key=>$val){
                //查询商品信息
                $goods = Db::name('goods')->where([
                    'id'=>$val
                ])->field('id,name,type,price,image')->find();
//                var_dump($goods);
                $goods_id[] = [
                    'goods_id'=>$goods['id'],
                    'goods_name'=>$goods['name'],
                    'goods_type'=>$goods['type'],
                    'goods_price'=>$goods['price'],
                    'goods_image'=>$goods['image'],
                    'goods_number'=>$post['number'][$key]
                ];
                //统计定气数量
                $bottle_num+=$post['number'][$key];
                if($goods['type']==1){
                    $new_bottle_num+=1;
                }
                //[{"goods_id":6,"goods_name":"煤气罐空瓶（不带气）","goods_number":1,"goods_type":1,"goods_price":"0.00","goods_image":"https:\/\/xtfhrq.cn\/uploads\/images\/20230815220804256f06437.gif"}]
            }
//            var_dump($goods_id);die;
            //1.生成订单信息
            $orderData = [
                'order_sn'=>createSn('order', 'order_sn'),
                'goods_id'=>json_encode($goods_id),//要统计
                'site_id'=>$post['site_id']??1,
                'admin_id'=>$this->admin_id,
                'order_source'=>2,
                'delivery_type'=>1,
                'user_remark'=>$post['user_remark']??'',
                'settle_bottle_rent'=>$post['settle_bottle_rent'],
                'floor_amount'=>$post['floor_amount'],
                'bottle_deposit'=>$post['bottle_deposit'],
                'bottle_amount'=>$post['bottle_amount'],
                'order_amount'=>$post['order_amount'],
                'bottle_num'=>$bottle_num,//定气数量
                'new_bottle_num'=>$new_bottle_num,//新增押瓶数量（是主产品需要+1，增购产品无需增加）
                'is_recovery'=>$post['is_recovery']??0,//是否需要旧瓶回收 0-否1-是
                'order_status'=>1,
                'pay_status'=>1,
                'pay_time'=>date('Y-m-d H:i:s',time()),
                'create_time'=>date('Y-m-d H:i:s',time()),
                'user_id'=>$post['user_id'],
                'consignee'=>$post['name'],
                'address'=>$post['address'],
                'address_detail'=>$post['address_detail'],
                'mobile'=>$post['mobile'],
                'floor'=>$post['floor'],
                'if_elevator'=>$post['if_elevator'],
                'latitude'=>$post['latitude'],
            ];
//            var_dump($orderData);
            $orderId = Db::name('order')->insertGetId($orderData);
            $this->_success('下单成功',$orderId);
        }
    }

    /**
     * User: 意象信息科技 mjf
     * Desc: 确认收货
     */
    public function confirm()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post('');
            $check = $this->validate($post, 'app\admin\validate\Order.confirm');
            if (true !== $check) {
                $this->_error($check);
            }
            OrderLogic::confirm($post['order_id'], $this->admin_id);
            $this->_success('确认成功');
        }
    }

    /**
     * User: 意象信息科技 mjf
     * Desc: 物流信息
     */
    public function express()
    {
        $id = $this->request->get('id');
        $detail = OrderLogic::getDetail($id);
        $detail['shipping'] = OrderLogic::shippingInfo($detail['id']);
        $this->assign('detail', $detail);
        return $this->fetch();
    }

    public function remarks()
    {
        // 获取的
        if ($this->request->isAjax() && $this->request->isGet()){
            $get = $this->request->get();
            $detail = OrderLogic::remarks($get, 'get');
            $this->_success('获取成功', $detail);
        }

        // 提交的
        if ($this->request->isAjax() && $this->request->isPost()) {
            $post = $this->request->post();
            $result = OrderLogic::remarks($post, 'post');
            if ($result) {
                $this->_success('保存成功');
            }
            $this->error('保存失败');
        }

    }

    /**
     * Notes:打印接口
     */
    public function orderPrint(){
        $id = $this->request->post('id');
        $result = $this->validate(['id'=>$id],'app\admin\validate\OrderPrint');
        if(true === $result){
            $result = OrderLogic::orderPrint($id);
            if(true === $result){
                $this->success('打印机成功，如未出小票，请检查打印机是否在线');
            }
        }
        $this->_error($result);
    }
}